<template>
  <div class="form">
    <div class="title">小艺人：{{ state.starinfo?.star?.name }}</div>
    <div class="upload" v-for="(item, index) in state.photos" :key="index">
      <label>
        <input
          type="file"
          accept="image/*"
          @change="inputChange($event, index)"
        />
        <img :src="state.photos[index]" v-if="state.photos[index]" />
      </label>
      <div class="loader" v-if="state.uploading[index]"></div>
      <div
        class="remove"
        v-if="state.photos[index]"
        @click="removeImg($event, index)"
      ></div>
    </div>
    <button class="submit" @click="saveImg">保存</button>
  </div>
</template>

<script setup>
import { useRouter, useRoute } from "vue-router";
import ajax from "../../util/http";
import { reactive, ref, computed, getCurrentInstance } from "vue";
const { proxy } = getCurrentInstance();

const router = useRouter();
const route = useRoute();

const state = reactive({
  starinfo: {},
  photos: [null, null],
  uploading: [false, false],
});

ajax
  .post("/star/scene/oper_table", {
    token: JSON.parse(localStorage.getItem("userinfo")).token,
    checkin_no: route.query.checkin_no,
    checkin_stage: route.query.checkin_stage,
  })
  .then((res) => {
    if (res.code == 1) {
      state.starinfo = res.data;
      if (res.data.register.prtest_photo) {
        let photos = res.data.register.prtest_photo.split(",");

        if (photos.length <= 1) {
          state.photos[0] = res.data.register.prtest_photo;
        } else {
          state.photos = photos;
        }
      }
    }
  });

const inputChange = (e, idx) => {
  state.uploading[idx] = true;
  let formData = new FormData();
  formData.append("file", e.target.files[0]);
  ajax.post("/common/upload", formData).then((res) => {
    if (res.code == 1) {
      state.uploading[idx] = false;
      state.photos[idx] = res.data.fullurl;
    }
  });
};

const removeImg = (event, idx) => {
  delete state.photos[idx];
};
const saveImg = () => {
  let photos = state.photos.filter((item) => item && item.trim()).join(",");
  if (photos) {
    ajax
      .post("/star/scene/modi_table", {
        token: JSON.parse(localStorage.getItem("userinfo")).token,
        checkin_id: route.query.checkin_stage
          ? state.starinfo.checkin1.id
          : state.starinfo.checkin2.id,
        prtest_photo: state.photos
          .filter((item) => item && item.trim())
          .join(","),
      })
      .then((res) => {
        if (res.code == 1) {
          router.push("/photographer/success");
        }
      });
  } else {
    proxy.$message({ content: "请至少上传一张图片" });
  }
};
</script>